package utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @author 栋
 * @date 2022/11/6
 * @description JDBC工具类
 */
public class JdbcUtils {
    private static DruidDataSource dataSource;
    static {
        try {
            Properties properties=new Properties();
            InputStream is = JdbcUtils.class.getClassLoader().getResourceAsStream("druid-config.properties");
            properties.load(is);
            dataSource = (DruidDataSource)DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取链接
     * @return 返回链接
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        DruidPooledConnection conn = dataSource.getConnection();
        return conn;
    }

    /**
     * 关闭资源
     * @param conn
     */
    public static void closeResoure(Connection conn){
        try {
            if(conn!=null)
                conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void closeResoure(Connection conn, Statement s){
        try {
            if(conn!=null)
                conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if(s!=null)
                s.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void closeResoure(Connection conn, Statement s, ResultSet rs){
        try {
            if(conn!=null)
                conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if(s!=null)
                s.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if(rs!=null)
                rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
